<?php

/**
 * @author chenshubo
 * 候鸟订单
 */
namespace App\Service\OrderService\OrderRouteService;
use App\Service\Code\Normal;
use App\Model\PssModel\OrderSupplier;
use Service\AppService\IdService;
use App\Service\TaskServer\TaskWorker;
use App\Service\Sms\SendSmsCode;
use App\Service\OrderService\BaseSupplierRouterService;
use App\Service\VendorClient\ShopHouNiaoApi\ShopHouNiaoApiClient;

class Shophouniao extends BaseSupplierRouterService
{ 
    /**
     * 创建订单
     * @param array $param
     * @return mixed
     */
    public function createOrder( $param = [] )
    {
        //生成供应商主单号
        $supplierGoodsInfo  = $param['supplierGoodsInfo'];
        $supplierCode       = $supplierGoodsInfo['supplierCode'];
        $userGoodsList      = $supplierGoodsInfo['userGoodsList'];
        $payDeclare         = $supplierGoodsInfo['payDeclare'];
        $supplierCode       = $supplierGoodsInfo['supplierCode'];
        //下游是否申报
        $isDelare = (
            (isset($param['order']['isOrderDeclare']) && $param['order']['isOrderDeclare'] == 1) ||
            (isset($param['order']['isPayDeclare']) && $param['order']['isPayDeclare'] == 1)
            ) ? true : false;
        
        //是否云仓商城
        $isShop = isset($param['order']['isSplitOrder']) && $param['order']['isSplitOrder'] == 1 ? true : false ;
        
        //做了支付单申报或者订单申报或者云仓商城
        if( $isDelare && !$isShop )
        {
            $param['order']['supplier_dsn'] = $param['order']['orderSn'];
        }
        
        $param['order']['supplier_psn'] = OrderSupplier::instance()->getCreateOrderSn($supplierCode);
        
        //调用上游创建订单接口
        $res = $this->callSdkApi(ShopHouNiaoApiClient::class,$param['apiBody'])->createOrder($param);
        if( $res['code'] != Normal::SUC ) {
            return $res;
        }
        $parameter = [
            [
                'tag'       => $supplierCode,
                'uid'       => $param['order']['supplier_psn'],
                'url'       => $res['data']['url'],
                'data'      => json_encode($res['data']['data'],JSON_UNESCAPED_UNICODE),
                'method'    => 'post',
                'param'     => json_encode($param,JSON_UNESCAPED_UNICODE),
                'format'    => $res['data']['format'],
                'header'    => [],
            ]
        ];
        return Normal::returnCode(Normal::SUC,"获取订单参数成功",[
            'orderPush' => $parameter
        ]);
    }
    
    /**
     * 订单支付
     * @param array $param
     * @return mixed
     */
    public function orderPay( $param = [] ) 
    {
        $orderInfo  = $param['supplierOrder'];
        $orderGoods = $param['orderGoods'];
        
        //获取仓库信息
        $notifyReduceStock = [];
        foreach ($orderGoods as $item ) {
            $notifyReduceStock[] = [
                'warehouseID'           => $item['store_id'],
                'stockInfoID'           => $item['stock_id'],
                'number'                => bcmul((string)$item['quantity'], (string)$item['spec_num']),
            ];
            unset($item);
        }
        
        //获取总部ERP 消耗库存通知接口地址
        $groupErpNotifyUrl   = config('gateway_net.yx_reduceStock');
        if( empty($groupErpNotifyUrl) ) {
            return Normal::returnCode(Normal::FAIL,"通知地址配置不能为空");
        }
        
        //调用候鸟支付接口
        $res = $this->callSdkApi(ShopHouNiaoApiClient::class,$param['apiBody'])->orderPay([
            'order_no' => $orderInfo['supplier_csn'],
        ]);
        
        if( $res['code'] != Normal::SUC ) {
            return $res;
        }
        
        $systemInfoID = config('gateway_net.systemID');
        $parameter = [
            [
                'tag'       => 'houniao_pay',
                'uid'       => IdService::instance()->getOtherID(),
                'url'       => $res['data']['url'],
                'data'      => $res['data']['data'],
                'method'    => 'post',
                'format'    => $res['data']['format'],
                'header'    => [
                    "Content-Type: application/form-data"
                ]
            ],
           /*  [
                'tag'       => 'yx_reduceStock',
                'uid'       => IdService::instance()->getOtherID(),
                'url'       => config('gateway_net.yx_reduceStock'),
                'data'      => ['stockInfoConsumes'=>$notifyReduceStock],
                'method'    => 'post',
                'format'    => 'json',
                'header'    => [
                    "systemID: {$systemInfoID}",
                    "Content-Type: application/json"
                ]
            ] */
        ];
        
        $resTask = TaskWorker::instance()->addTask($parameter);
        $result = [];
        foreach ($resTask as $item ) {
            $result[$item['request']['tag']] = $item['response'];
            unset($item);
        }
        
        $res = $this->getOrderPayCode($result['houniao_pay']);
        if( isset($res['code']) && $res['code'] == Normal::SUC )
        {
            return Normal::returnCode(Normal::SUC,"支付成功",[
                'orderItem' => [
                    'orderSn'           => $orderInfo['order_sn'],
                    'realTotalMoney'    => $orderInfo['real_total_money'],
                    'deliverMoney'      => $orderInfo['deliver_money'],
                    'goodsMoney'        => $orderInfo['goods_money'],
                    'discountMoney'     => $orderInfo['discount_money'],
                ]
            ]);
        }
        
        //只有余额不足的情况下才进行通知
        if( isset($res['code']) && $res['code'] == '10015' ) {
            SendSmsCode::instance()->notifyPayMobileMessage("【候鸟】预存款不足，请及时充值。如6小时未充值，订单会自动取消。",config('api.houniao.acount.smsNotifyMobile'));
        }
        
        return $res;
    }
    
    /**
     * 订单取消
     * @param array $param
     * @return mixed
     */
    public function orderCancel( $param = [] ) 
    {
        $res = $this->callSdkApi(ShopHouNiaoApiClient::class,$param['apiBody'])->orderCancel([
            'orderNo'       => $param['supplierOrder']['supplier_csn'],
            'exceptReason'  => $param['order']['exceptReason']
        ]);
        
        if( $res['code'] != Normal::SUC ) {
            return $res;
        }
        
        $parameter = [
            [
                'tag'       => 'houniao_cancel',
                'uid'       => IdService::instance()->getOtherID(),
                'url'       => $res['data']['url'],
                'data'      => $res['data']['data'],
                'method'    => 'post',
                'format'    => $res['data']['format'],
                'header'    => []
            ],
        ];
        
        $resTask = TaskWorker::instance()->addTask($parameter);
        $result = [];
        foreach ($resTask as $item ) {
            $result[$item['request']['tag']] = $item['response'];
            unset($item);
        }
        
        return $this->getOrderPayCode($result['houniao_cancel']);
    }
    
    /**
     * 订单售后
     * @param array $param
     * @return mixed
     */
    public function orderAfterSale($param = [])
    {
        return Normal::returnCode(Normal::SUC,"处理完成");
    }
 
    /**
     * 获取返回值
     * @param string $param
     */
    public function getOrderPayCode( array $param ) 
    {
        $result = @json_decode($param['result'],true);
        if( isset($result['code']) && $result['code'] == 0 ) {
            return Normal::returnCode(Normal::SUC,$result['message']??'支付成功');
        }
        return Normal::returnCode( isset($result['code']) ? $result['code'] : 0 ,$result['message']??'支付失败');
    }
    
    /**
     * 获取响应code
     * @param array $param
     */
    public function getCreateOrderCode( $param = [])
    {
        $result = @json_decode($param['result'],true);
        if( !empty($result['errorOrders']) ) {
            $msg = implode("|", array_column($result['errorOrders'], 'message'));
            return Normal::returnCode(Normal::FAIL,$msg);
        }
        
        if( empty($result['successOrders']) ) {
            return Normal::returnCode(Normal::FAIL,"请求失败，请稍后再试");
        }
        
        $successOrders = current($result['successOrders']);
        $orderItems = [];
        foreach ($successOrders['orderItems'] as $item )
        {
            $orderItems[] = [
                'supplier_dsn' => IdService::instance()->getOtherID(),
                'supplier_csn' => $item['orderNo'],
                'orderGoods'   => $item['goods_items']
            ];
            unset($item);
        }
        
        return Normal::returnCode(Normal::SUC,"OK",[
            'orderList' => $orderItems,
        ]);
    }
}